<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 车辆台账详情 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading">
        <!-- 车辆基本信息 -->
        <a-card :bordered="false">
          <title-name title="车辆基本信息" />
          <custom-form :form-list="baseForm" :form="form" :edit-model="editModel == 0 ? 'V' : ''" />
        </a-card>
        <!-- 购置信息 -->
        <a-card v-if="form.carNature === 'GZ'" :bordered="false">
          <title-name title="购置信息" />
          <custom-form :form-list="buyForm" :form="form" :edit-model="editModel == 0 ? 'V' : ''" />
        </a-card>
        <!-- 租赁信息 -->
        <a-card v-if="form.carNature === 'ZN'" :bordered="false">
          <title-name title="租赁信息" />
          <custom-form :form-list="rentForm" :form="form" :edit-model="editModel == 0 ? 'V' : ''" />
        </a-card>
        <!-- 其他 -->
        <a-card :bordered="false">
          <title-name title="其他" />
          <custom-form :form-list="otherForm" :form="form" :edit-model="editModel == 0 ? 'V' : ''" />
        </a-card>
        <!-- 车辆档案 -->
        <a-card :bordered="false">
          <title-name title="车辆档案" />
          <custom-form :form-list="fileForm" :form="form" :edit-model="editModel == 0 ? 'V' : ''">
            <!-- 附件上传 -->
            <template v-for="item in form.fileList" #[item.label]>
              <div :key="item.value" class="file_item">
                <template v-if="editModel != 0">
                  <l-table :file-auto-loading="false" business-code="OF12" :upload-arrys.sync="item.fileVOS" />
                </template>
                <file-link v-else :file-list="item.fileVOS" />
              </div>
            </template>
          </custom-form>
          <div v-if="editModel != 0" style="color: #999; padding-left: 130px">
            支持格式：.rar .zip .doc .docx .pdf .jpg .png
          </div>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button v-if="editModel != 0" :loading="loading" type="primary" class="button_right" @click="handleSubmit">
          提交
        </a-button>
        <a-button type="primary" @click="handleActiveClose">
          关闭
        </a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
import { carInfo } from '@/api/office/vehicle/config' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import Selector from '@/components/Select/Selector' // 人员
import SelectDriver from '@/components/Select/SelectDriver' // 枚举
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject' // 申请单位
export default {
  extends: new BaseEditPage(),
  data() {
    return {
      fileList: [
        { value: '0', label: '购置申请' },
        { value: '1', label: '购置批复' },
        { value: '2', label: '询价记录' },
        { value: '3', label: '购车合同' },
        { value: '4', label: '车辆一致性证书' },
        { value: '5', label: '购车发票' },
        { value: '6', label: '完税证明' },
        { value: '7', label: '首期保险' },
        { value: '8', label: '行驶证' },
        { value: '9', label: '车辆登记证' },
        { value: '10', label: '驾驶证' },
        { value: '11', label: '固定资产验收单' },
        { value: '12', label: '其他' }
      ], // 默认文件列表
      loading: false, // 提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        carNature: 'GZ',
        fileList: []
      }, // 表单
      rules: {
        carNature: [{ required: true, message: '请选择车辆性质', trigger: 'change' }],
        carNumber: [{ required: true, whitespace: true, message: '请输入车牌号', trigger: 'change' }],
        brand: [{ required: true, whitespace: true, message: '请输入品牌型号', trigger: 'change' }],
        engineNumber: [{ required: true, whitespace: true, message: '请输入发动机号', trigger: 'change' }],
        gas: [{ required: true, whitespace: true, message: '请输入排气量', trigger: 'change' }],
        chassisNumber: [{ required: true, whitespace: true, message: '请输入车架号', trigger: 'change' }],
        carType: [{ required: true, message: '请选择车辆类型', trigger: 'change' }],
        color: [{ required: true, whitespace: true, message: '请输入车身颜色', trigger: 'change' }],
        state: [{ required: true, message: '请选择状态', trigger: 'change' }],
        buyUnitId: [{ required: true, message: '请选择购置单位', trigger: 'change' }],
        buyTime: [{ required: true, message: '请选择购置时间', trigger: 'change' }],
        buyAmount: [{ required: true, message: '请输入购置总金额（元）', trigger: 'change' }],
        carPrice: [{ required: true, message: '请输入车辆裸车价（元）', trigger: 'change' }],
        rentUnitName: [{ required: true, whitespace: true, message: '请输入租车单位', trigger: 'change' }],
        rentTime: [{ required: true, message: '请选择租赁期限', trigger: 'change' }],
        carCost: [{ required: true, message: '请输入租车费用（元/月，不含司机）', trigger: 'change' }],
        driverCost: [{ required: true, message: '请输入司机费用（元/月）', trigger: 'change' }],
        auditTime: [{ required: true, message: '请选择年审日期', trigger: 'change' }]
      }, // 校验规则
      init: false // 初始化标识
    }
  },
  watch: {
    // 监听车辆性质清空随车司机
    'form.carNature'() {
      if (this.init) {
        if (this.form.driverId) {
          this.form.driverId = void 0
        } else {
          this.$set(this.form, 'driverId', void 0)
        }
      }
    }
  },
  mounted() {
    this.$route.meta.title = ['车辆台账查看', '车辆台账编辑', '车辆台账新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      carInfo
        .detail({ id: this.id })
        .then((res) => {
          this.loading = false
          // 格式化限行时间
          if (res.data.forbid) {
            res.data.forbid = res.data.forbid.split(',')
          }
          // 格式化文件
          if (!res.data.fileList || res.data.fileList.length === 0) {
            res.data.fileList = this.fileList
          }
          // 格式化租赁时间
          if (res.data.rentStartTime && res.data.rentEndTime) {
            res.data.rentTime = [res.data.rentStartTime, res.data.rentEndTime]
          }
          // 格式化购置单位
          if (res.data.buyUnitName && res.data.buyUnitId) {
            res.data.buyUnitId = {
              label: res.data.buyUnitName,
              value: res.data.buyUnitId
            }
          }
          // 映射表单
          this.form = res.data
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      const post = this.$currentPost()
      // 默认状态为可用
      this.$set(this.form, 'state', '1')
      // 默认驾驶员性质为购置
      this.$set(this.form, 'carNature', 'GZ')
      // 初始化单位
      this.$set(this.form, 'unitName', (post.code === 'PD' ? post.orgName + '-' : '') + post.name)
      this.$set(this.form, 'unitId', post.id)
      // 初始化购置单位
      this.$set(this.form, 'buyUnitId', {
        label: post.name,
        value: post.id
      })
      this.form.fileList = this.fileList
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  computed: {
    // 车辆基本信息
    baseForm() {
      return [
        {
          keyName: 'unitName',
          type: 'BaseInput',
          disabled: true,
          label: '所属单位'
        },
        {
          keyName: 'carNature',
          viewName: 'carNatureName',
          label: '车辆性质',
          type: Selector,
          attrs: {
            selectType: '48',
            valueName: 'code',
            urlType: 'union'
          }
        },
        {
          keyName: 'carNumber',
          type: 'BaseInput',
          label: '车牌号'
        },
        {
          keyName: 'brand',
          type: 'BaseInput',
          label: '品牌型号'
        },
        {
          keyName: 'carType',
          viewName: 'carTypeName',
          label: '车辆类型',
          type: Selector,
          attrs: {
            selectType: '21',
            valueName: 'code',
            urlType: 'union'
          }
        },
        {
          keyName: 'color',
          type: 'BaseInput',
          label: '车身颜色'
        },
        {
          keyName: 'engineNumber',
          type: 'BaseInput',
          label: '发动机号'
        },
        {
          keyName: 'gas',
          type: 'BaseInput',
          label: '排气量'
        },
        {
          keyName: 'chassisNumber',
          type: 'BaseInput',
          label: '车架号'
        },
        {
          keyName: 'forbid',
          type: 'a-select',
          label: '限行时间',
          placeholder: '请选择限行时间',
          attrs: {
            mode: 'multiple',
            maxTagCount: 3
          },
          data: [
            {
              label: '周一',
              value: '周一'
            },
            {
              label: '周二',
              value: '周二'
            },
            {
              label: '周三',
              value: '周三'
            },
            {
              label: '周四',
              value: '周四'
            },
            {
              label: '周五',
              value: '周五'
            },
            {
              label: '周六',
              value: '周六'
            },
            {
              label: '周日',
              value: '周日'
            }
          ],
          customRender() {
            return arguments[0]?.join('，') ?? '无'
          }
        },
        {
          keyName: 'state',
          viewName: 'stateName',
          label: '状态',
          type: Selector,
          attrs: {
            selectType: '15',
            valueName: 'code',
            urlType: 'union'
          }
        }
      ]
    },
    // 购置信息
    buyForm() {
      return [
        {
          keyName: 'buyUnitId',
          viewName: 'buyUnitName',
          type: SelectCompanyAndProject,
          label: '购置单位',
          attrs: {
            labelInValue: true,
            treeDefaultExpandAll: true,
            isAuth: false
          }
        },
        {
          keyName: 'buyTime',
          type: 'a-date-picker',
          placeholder: '请选择购置时间',
          label: '购置时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'buyAmount',
          type: 'BaseInputNumber',
          label: '购置总金额（元）',
          precision: 2,
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'carPrice',
          type: 'BaseInputNumber',
          label: '车辆裸车价（元）',
          precision: 2,
          attrs: {
            min: 0
          }
        }
      ]
    },
    // 租赁信息
    rentForm() {
      return [
        {
          keyName: 'rentUnitName',
          // viewName: 'rentUnitName',
          type: 'BaseInput',
          label: '租车单位'
        },
        {
          keyName: 'rentTime',
          type: 'a-range-picker',
          placeholder: ['请选择租赁期限', '请选择租赁期限'],
          label: '租赁期限',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          },
          customRender() {
            return arguments[0]?.length > 0 ? arguments[0][0] + ' 至 ' + arguments[0][1] : '无'
          }
        },
        {
          keyName: 'carCost',
          type: 'BaseInputNumber',
          label: '租车费用（元/月，不含司机）',
          precision: 2,
          attrs: {
            min: 0
          }
        },
        {
          keyName: 'driverCost',
          type: 'BaseInputNumber',
          label: '司机费用（元/月）',
          precision: 2,
          attrs: {
            min: 0
          }
        }
      ]
    },
    // 其他信息
    otherForm() {
      return [
        {
          keyName: 'driverId',
          viewName: 'driverName',
          type: SelectDriver,
          label: '随车司机',
          attrs: {
            attr: {
              // driverTypeId: this.form.carNature,
              unitId: this.form.unitId,
              driverName: this.form.driverName
            }
          }
        },
        {
          keyName: 'auditTime',
          type: 'a-date-picker',
          placeholder: '请选择年审日期',
          label: '年审日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'gasCardNumber',
          type: 'BaseInput',
          label: '加油卡号'
        }
      ]
    },
    // 车辆档案
    fileForm() {
      return this.form.fileList.map((item) => ({
        slot: true,
        keyName: item.label,
        label: item.label
      }))
    }
  },
  methods: {
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          let name = ['update', 'create'][that.editModel - 1] // 根据操作切换url地址
          // 提交表单
          let form = that.$clone(that.form)
          let file = form.fileList?.map((item) => {
            return {
              label: item.label,
              file: item.fileVOS?.map((i) => i.commonId)?.join()
            }
          }) // 文件参数
          form.forbid && (form.forbid = form.forbid.join())
          // 格式化文件
          form.file = file ? JSON.stringify(file) : void 0
          // 格式化购置单位
          if (form.buyUnitId) {
            form.buyUnitName = form.buyUnitId.label
            form.buyUnitId = form.buyUnitId.value
          }
          // 格式化租赁时间
          if (form.rentTime?.length > 0) {
            form.rentStartTime = form.rentTime[0]
            form.rentEndTime = form.rentTime[1]
          }
          delete form.fileList
          if (that.editModel == 2) {
            form.level = that.$currentPost().code
          }
          // 提交表单
          that.loading = true
          carInfo[name](form)
            .then(() => {
              that.loading = false
              that.$message.success('提交成功！')
              that.$multiTab.close()
            })
            .catch(() => {
              that.loading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.file_item {
  margin-top: -3px;
}

/deep/.ant-form-item {
  .ant-form-item-label {
    height: 28px;
    width: 220px;
    line-height: 22px;
    padding: 6px 4px 0 0;
    text-align: right;
    white-space: pre-wrap;
    overflow: visible;
  }

  .ant-form-item-control-wrapper {
    width: calc(100% - 220px);
  }
}
</style>